/* eslint-disable default-case */
/* eslint-disable consistent-return */
import { message } from 'antd';
import { getProtList, getDownloadInfo, getUploadProgress, uploadFileProt } from '@/services/changeprot';
import * as service from '@/services/socket';

export default {
  state: {
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
      // 更换协议
      changeType: '1',
      oldSuppId: undefined, // 原供应商
      suppId: undefined,
      suppProtId: undefined,
    },
    supplyList: [],
    protList: [],
    custName: '',
    areaName: '',
    detList: [],
    isGoBack: false,
    currentStep: 0,
    showProgress: false,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/nsApi/sendService/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    // 获取协议列表
    *fetchProtList({ payload }, { call, put }) {
      const response = yield call(getProtList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          protList: [],
        },
      });
      if (response.success) {
        if (!response.data.totalCount) {
          return message.warning('该供应商下暂无协议！');
        }
        yield put({
          type: 'updateModelData',
          payload: {
            protList: response.data.pageRecords || [],
          },
        });
      } else {
        message.warning(`${response.message || '获取供应商协议：服务端错误！'}`);
      }
    },
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    *uploadFileWithProgress({ payload }, { call, put }) {
      const response = yield call(uploadFileProt, payload);
      if (response.success) {
        if (response.data && response.data.successProp !== 100) {
          yield call(service.socketChannel, {
            type: 'sub',
            data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          });
        } else {
          yield put({
            type: 'updateBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '上传失败'}`);
      }
      return response;
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
      }
      return {
        ...state,
        showProgress,
        progressPercent: payload.successProp,
        resultInfo,
        currentStep,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'task':
            dispatch({
              type: 'updateBatchTask',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
